﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
//using OpenNETCF.Net;
using OpenNETCF.Net.NetworkInformation;

namespace test
{
    public class Wifi
    {
        private System.Windows.Forms.Timer wifiTimer = new System.Windows.Forms.Timer();
        private List<WifiData> nearbyAPs =new List<WifiData>();
        private WirelessZeroConfigNetworkInterface m_wzc = null;
       // private AdapterCollection adapters;

        public Wifi()
        {
            wifiTimer.Interval = 5000;
            wifiTimer.Tick +=new EventHandler(wifiTimer_Tick);
            FindWirelessAdapter();
            UpdateAPs();
        }

        private void wifiTimer_Tick(object sender, EventArgs e)
        {
            UpdateAPs();
        }

        private void FindWirelessAdapter()
        {
            foreach (INetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (ni is WirelessNetworkInterface)
                {
                    if (ni is WirelessZeroConfigNetworkInterface)
                    {
                        m_wzc = ni as WirelessZeroConfigNetworkInterface;
                    }
                    break;
                }
            }
        }
        private void UpdateAPs()
        {

            if (m_wzc == null) return;
            nearbyAPs.Clear();
            foreach (OpenNETCF.Net.NetworkInformation.AccessPoint ap in m_wzc.NearbyAccessPoints)
            {
                WifiData wd = new WifiData();
                wd.MacAddress = ap.PhysicalAddress.GetAddressBytes();
                wd.Name = ap.Name;
                wd.Rssi = ap.SignalStrength.Decibels;
                nearbyAPs.Add(wd);
                
            }
        }
        public bool GetRadioStatus()
        {
            return wifiTimer.Enabled;
        }
        public int SetRadioOn()
        {
            try
            {
                wifiTimer.Enabled = true;
            }
            catch
            {
                return 1;
            }
            return 0;
        }
        public int SetRadioOff()
        {
            try
            {
               wifiTimer.Enabled = false;
            }
            catch
            {
                return 1;
            }
            return 0;
        }
        public int SetRadioOn(int interval)
        {
            throw new NotImplementedException();
        }
        public int SetRadioOff(int interval)
        {
            throw new NotImplementedException();
        }
        
        public int DataRequest()
        {
            throw new NotImplementedException();
        }
        public List<WifiData> GetData()
        {
            return nearbyAPs;
        }
    }
}
